﻿using SqlsugarService.Application.DTOs.ProductionOrderDto;
using SqlsugarService.Application.IService.ProductionOrders;
using SqlsugarService.Application.Until;
using SqlsugarService.Domain.Plan;
using SqlsugarService.Infrastructure.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using SqlsugarService.Application.IService.Plan;
using SqlsugarService.Application.DTOs.PlanDto;
using SqlsugarService.Application.IService.Process.BomManagement;
using SqlsugarService.Application.DTOs.Process;

namespace SqlsugarService.Application.Service.ProductionOrders
{
    public class ProductionOrderService: IProductionOrderService
    {
        private readonly IBaseRepository<ProductionOrder> productionorderbase;
        private readonly IBaseRepository<ProductionPlan> productionPlanRepository;
        private readonly IBaseRepository<WorkOrderTaskEntity> workOrderTaskRepository;
        private readonly IProductionPlanService _productionPlanService;
        private readonly IMapper _mapper;
        private readonly IBomService _bomService;

        public ProductionOrderService(
            IBaseRepository<ProductionOrder> productionorderbase, 
            IBaseRepository<ProductionPlan> productionPlanRepository,
            IBaseRepository<WorkOrderTaskEntity> workOrderTaskRepository,
            IProductionPlanService productionPlanService,
            IMapper mapper,
            IBomService bomService)
        {
            this.productionorderbase = productionorderbase;
            this.productionPlanRepository = productionPlanRepository;
            this.workOrderTaskRepository = workOrderTaskRepository;
            this._productionPlanService = productionPlanService;
            this._mapper = mapper;
            this._bomService = bomService;
        }
        
        /// <summary>
        /// 获取生产工单分页列表
        /// </summary>
        /// <param name="search">搜索条件</param>
        /// <returns>分页结果</returns>
        public async Task<ApiResult<PageResult<List<GetProductionOrderDto>>>> GetProductionOrderList(GetProductionOrderSearchDto search)
        { 
            try
            {
                // 获取所有生产工单数据
                var query = await productionorderbase.GetAllAsync();
                
                // 根据搜索条件进行过滤
                if (!string.IsNullOrEmpty(search.OrderNumber))
                {
                    query = query.Where(x => x.OrderNumber.Contains(search.OrderNumber) || 
                                           x.OrderName.Contains(search.OrderNumber)).ToList();
                }
                
                if (!string.IsNullOrEmpty(search.ProductName))
                {
                    query = query.Where(x => x.ProductName.Contains(search.ProductName) || 
                                           x.ProductNumber.Contains(search.ProductName)).ToList();
                }
                
                if (!string.IsNullOrEmpty(search.Status))
                {
                    query = query.Where(x => x.Status == search.Status).ToList();
                }

                // 计算总数和总页数
                var totalCount = query.Count();
                var totalPage = (int)Math.Ceiling(totalCount * 1.0 / search.PageSize);

                // 分页查询
                var productionOrders = query
                    .OrderByDescending(x => x.CreatedAt) // 按创建时间倒序排列
                    .Skip((search.PageIndex - 1) * search.PageSize)
                    .Take(search.PageSize)
                    .ToList();

                // 映射为DTO
                var result = _mapper.Map<List<GetProductionOrderDto>>(productionOrders);

                // 返回分页结果
                return ApiResult<PageResult<List<GetProductionOrderDto>>>.Success(
                    new PageResult<List<GetProductionOrderDto>>
                    {
                        TotalCount = totalCount,
                        TotalPage = totalPage,
                        Data = result
                    },
                    ResultCode.Success);
            }
            catch (Exception ex)
            {
                return ApiResult<PageResult<List<GetProductionOrderDto>>>.Fail($"获取生产工单列表失败：{ex.Message}", ResultCode.Error);
            }
        }

        /// <summary>
        /// 根据生产工单列表获取物料信息
        /// </summary>
        /// <param name="search">搜索条件</param>
        /// <returns>包含物料信息的生产工单列表</returns>
        public async Task<ApiResult<PageResult<List<GetProductionOrderWithMaterialsDto>>>> GetProductionOrderListWithMaterials(GetProductionOrderSearchDto search)
        {
            try
            {
                // 1. 获取生产工单列表
                var orderListResult = await GetProductionOrderList(search);
                if (!orderListResult.IsSuc)
                {
                    return ApiResult<PageResult<List<GetProductionOrderWithMaterialsDto>>>.Fail(orderListResult.Msg, ResultCode.Error);
                }

                var productionOrders = orderListResult.Data.Data;
                var result = new List<GetProductionOrderWithMaterialsDto>();

                // 2. 遍历生产工单，获取每个工单对应的生产计划
                foreach (var order in productionOrders)
                {
                    var orderWithMaterials = new GetProductionOrderWithMaterialsDto
                    {
                        // 复制生产工单基本信息
                        Id = order.Id,
                        OrderNumber = order.OrderNumber,
                        OrderName = order.OrderName,
                        ProductionPlanId = order.ProductionPlanId,
                        ProductId = order.ProductId,
                        ProductName = order.ProductName,
                        ProductNumber = order.ProductNumber,
                        Specification = order.Specification,
                        Unit = order.Unit,
                        PlanQuantity = order.PlanQuantity,
                        ActualQuantity = order.ActualQuantity,
                        PlanStartTime = order.PlanStartTime,
                        PlanEndTime = order.PlanEndTime,
                        Status = order.Status,
                        CreatedAt = order.CreatedAt,
                        UpdatedAt = order.UpdatedAt,
                        CreatedBy = order.CreatedBy,
                        UpdatedBy = order.UpdatedBy,
                        
                        // 初始化物料信息
                        Materials = new List<MaterialListItemDto>(),
                        BomId = Guid.Empty,
                        PlanName = "",
                        PlanNumber = "",
                        TotalMaterialQuantity = 0
                    };

                    // 3. 根据生产计划ID获取生产计划信息
                    if (order.ProductionPlanId != Guid.Empty)
                    {
                        var productionPlan = await productionPlanRepository.AsQueryable()
                            .Where(pp => pp.Id == order.ProductionPlanId && !pp.IsDeleted)
                            .FirstAsync();

                        if (productionPlan != null)
                        {
                            orderWithMaterials.BomId = productionPlan.BomId;
                            orderWithMaterials.PlanName = productionPlan.PlanName;
                            orderWithMaterials.PlanNumber = productionPlan.PlanNumber;

                            // 4. 根据BOM ID获取物料信息
                            if (productionPlan.BomId != Guid.Empty)
                            {
                                var materialsResult = await _productionPlanService.GetBomTreeStructure(productionPlan.BomId);
                                if (materialsResult.IsSuc && materialsResult.Data != null)
                                {
                                    // 5. 转换BOM树形结构为物料清单格式
                                    var materialList = ConvertBomTreeToMaterialList(materialsResult.Data, order.PlanQuantity);
                                    orderWithMaterials.Materials = materialList;
                                    
                                    // 6. 计算物料总量
                                    orderWithMaterials.TotalMaterialQuantity = materialList.Sum(m => m.EstimatedUsage);
                                }
                            }
                        }
                    }

                    result.Add(orderWithMaterials);
                }

                // 7. 返回结果
                return ApiResult<PageResult<List<GetProductionOrderWithMaterialsDto>>>.Success(
                    new PageResult<List<GetProductionOrderWithMaterialsDto>>
                    {
                        TotalCount = orderListResult.Data.TotalCount,
                        TotalPage = orderListResult.Data.TotalPage,
                        Data = result
                    },
                    ResultCode.Success);
            }
            catch (Exception ex)
            {
                return ApiResult<PageResult<List<GetProductionOrderWithMaterialsDto>>>.Fail($"获取生产工单物料信息失败：{ex.Message}", ResultCode.Error);
            }
        }

        /// <summary>
        /// 将BOM树形结构转换为物料清单格式
        /// </summary>
        /// <param name="bomTree">BOM树形结构</param>
        /// <param name="planQuantity">计划数量</param>
        /// <returns>物料清单列表</returns>
        private List<MaterialListItemDto> ConvertBomTreeToMaterialList(List<BomTreeStructureDto> bomTree, decimal planQuantity)
        {
            var materialList = new List<MaterialListItemDto>();
            var sequence = 1;

            // 递归处理BOM树形结构
            ProcessBomTreeNodes(bomTree, planQuantity, materialList, ref sequence);

            return materialList;
        }

        /// <summary>
        /// 递归处理BOM树节点
        /// </summary>
        /// <param name="nodes">BOM节点列表</param>
        /// <param name="parentQuantity">父级数量</param>
        /// <param name="materialList">物料清单列表</param>
        /// <param name="sequence">序号</param>
        private void ProcessBomTreeNodes(List<BomTreeStructureDto> nodes, decimal parentQuantity, List<MaterialListItemDto> materialList, ref int sequence)
        {
            foreach (var node in nodes)
            {
                // 计算实际使用量
                var actualQuantity = node.UsageQuantity * parentQuantity;

                // 创建物料清单项目
                var materialItem = new MaterialListItemDto
                {
                    Sequence = sequence++,
                    MaterialNumber = node.DisplayProductNumber ?? node.MaterialNumber ?? "未知编号",
                    MaterialName = node.DisplayName ?? node.MaterialName ?? "未知物料",
                    Specification = node.DisplaySpecification ?? node.MaterialSpecification ?? "未知规格",
                    Unit = node.Unit ?? "个",
                    EstimatedUsage = actualQuantity,
                    MaterialRatio = CalculateMaterialRatio(node, parentQuantity),
                    MaterialId = node.MaterialId,
                    Level = node.Level,
                    ParentItemId = node.ParentItemId
                };

                materialList.Add(materialItem);

                // 递归处理子节点
                if (node.Children != null && node.Children.Any())
                {
                    ProcessBomTreeNodes(node.Children, actualQuantity, materialList, ref sequence);
                }
            }
        }

        /// <summary>
        /// 计算用料比例
        /// </summary>
        /// <param name="node">BOM节点</param>
        /// <param name="parentQuantity">父级数量</param>
        /// <returns>用料比例字符串</returns>
        private string CalculateMaterialRatio(BomTreeStructureDto node, decimal parentQuantity)
        {
            try
            {
                // 计算比例：当前节点用量 / 父级数量 * 100%
                if (parentQuantity > 0)
                {
                    var ratio = (node.UsageQuantity / parentQuantity) * 100;
                    return $"{ratio:F1}%";
                }
                return "0%";
            }
            catch
            {
                return "0%";
            }
        }

        /// <summary>
        /// 获取生产工单的物料清单
        /// </summary>
        /// <param name="productionOrderId">生产工单ID</param>
        /// <returns>物料清单信息</returns>
        public async Task<ApiResult<MaterialListResultDto>> GetProductionOrderMaterialList(Guid productionOrderId)
        {
            try
            {
                // 1. 获取生产工单信息
                var productionOrder = await productionorderbase.AsQueryable()
                    .Where(po => po.Id == productionOrderId && !po.IsDeleted)
                    .FirstAsync();

                if (productionOrder == null)
                {
                    return ApiResult<MaterialListResultDto>.Fail("生产工单不存在或已被删除", ResultCode.Error);
                }

                // 2. 获取生产计划信息
                var productionPlan = await productionPlanRepository.AsQueryable()
                    .Where(pp => pp.Id == productionOrder.ProductionPlanId && !pp.IsDeleted)
                    .FirstAsync();

                if (productionPlan == null)
                {
                    return ApiResult<MaterialListResultDto>.Fail("关联的生产计划不存在或已被删除", ResultCode.Error);
                }

                // 3. 获取BOM物料信息
                var materialsResult = await _productionPlanService.GetBomTreeStructure(productionPlan.BomId);
                if (!materialsResult.IsSuc || materialsResult.Data == null)
                {
                    return ApiResult<MaterialListResultDto>.Fail("获取BOM物料信息失败", ResultCode.Error);
                }

                // 4. 转换BOM树形结构为物料清单格式
                var materialList = ConvertBomTreeToMaterialList(materialsResult.Data, productionOrder.PlanQuantity);

                // 5. 构建结果
                var result = new MaterialListResultDto
                {
                    ProductionOrderId = productionOrderId,
                    OrderNumber = productionOrder.OrderNumber,
                    OrderName = productionOrder.OrderName,
                    ProductName = productionOrder.ProductName,
                    ProductNumber = productionOrder.ProductNumber,
                    PlanQuantity = productionOrder.PlanQuantity,
                    Unit = productionOrder.Unit,
                    Materials = materialList,
                    TotalMaterialQuantity = materialList.Sum(m => m.EstimatedUsage)
                };

                return ApiResult<MaterialListResultDto>.Success(result, ResultCode.Success);
            }
            catch (Exception ex)
            {
                return ApiResult<MaterialListResultDto>.Fail($"获取物料清单失败：{ex.Message}", ResultCode.Error);
            }
        }

        /// <summary>
        /// 根据当前时间生成唯一的 ProductNumber，格式为 D + yyyyMMddHHmmss
        /// </summary>
        /// <returns></returns>
        private string GenerateProductNumberByTime()
        {
            var now = DateTime.Now;
            var timePart = now.ToString("yyyyMMddHHmmssfff");
            return $"GDBH{timePart}";
        }

        /// <summary>
        /// 根据生产工单ID获取工艺路线信息
        /// </summary>
        /// <param name="productionOrderId">生产工单ID</param>
        /// <param name="includeDeleted">是否包含已删除的工单，默认true</param>
        /// <returns>工艺路线信息</returns>
        public async Task<ApiResult<GetRoutingDto>> GetProductionOrderRouting(Guid productionOrderId, bool includeDeleted = true)
        {
            try
            {
                // 1. 根据生产工单ID获取生产工单信息
                var query = productionorderbase.AsQueryable().Where(po => po.Id == productionOrderId);
                
                // 如果不包含已删除的工单，则添加删除过滤条件
                if (!includeDeleted)
                {
                    query = query.Where(po => !po.IsDeleted);
                }
                
                var productionOrder = await query.FirstAsync();

                if (productionOrder == null)
                {
                    var message = includeDeleted ? 
                        $"生产工单不存在，ID: {productionOrderId}" : 
                        $"生产工单不存在或已被删除，ID: {productionOrderId}";
                    return ApiResult<GetRoutingDto>.Fail(message, ResultCode.Error);
                }

                // 2. 根据生产工单中的计划ID获取生产计划信息
                if (productionOrder.ProductionPlanId == Guid.Empty)
                {
                    return ApiResult<GetRoutingDto>.Fail("生产工单未关联生产计划", ResultCode.Error);
                }

                var productionPlan = await productionPlanRepository.AsQueryable()
                    .Where(pp => pp.Id == productionOrder.ProductionPlanId && !pp.IsDeleted)
                    .FirstAsync();

                if (productionPlan == null)
                {
                    return ApiResult<GetRoutingDto>.Fail($"关联的生产计划不存在，计划ID: {productionOrder.ProductionPlanId}", ResultCode.Error);
                }

                // 3. 根据生产计划中的BOM ID获取工艺路线信息
                if (productionPlan.BomId == Guid.Empty)
                {
                    return ApiResult<GetRoutingDto>.Fail("生产计划未关联BOM", ResultCode.Error);
                }

                var routingResult = await _bomService.GetRoutingByBomIdAsync(productionPlan.BomId);
                if (!routingResult.IsSuc)
                {
                    return ApiResult<GetRoutingDto>.Fail(routingResult.Msg ?? "获取工艺路线信息失败", routingResult.Code);
                }

                // 直接返回工艺路线信息，不需要额外查询
                return ApiResult<GetRoutingDto>.Success(routingResult.Data, ResultCode.Success);
            }
            catch (Exception ex)
            {
                return ApiResult<GetRoutingDto>.Fail($"获取生产工单工艺路线失败：{ex.Message}", ResultCode.Error);
            }
        }

        /// <summary>
        /// 根据生产工单ID获取工序信息
        /// </summary>
        /// <param name="productionOrderId">生产工单ID</param>
        /// <param name="includeDeleted">是否包含已删除的工单，默认true</param>
        /// <returns>工序信息列表</returns>
        public async Task<ApiResult<List<GetProcessDto>>> GetProductionOrderProcesses(Guid productionOrderId, bool includeDeleted = true)
        {
            try
            {
                // 1. 根据生产工单ID获取生产工单信息
                var query = productionorderbase.AsQueryable().Where(po => po.Id == productionOrderId);
                
                // 如果不包含已删除的工单，则添加删除过滤条件
                if (!includeDeleted)
                {
                    query = query.Where(po => !po.IsDeleted);
                }
                
                var productionOrder = await query.FirstAsync();

                if (productionOrder == null)
                {
                    var message = includeDeleted ? 
                        $"生产工单不存在，ID: {productionOrderId}" : 
                        $"生产工单不存在或已被删除，ID: {productionOrderId}";
                    return ApiResult<List<GetProcessDto>>.Fail(message, ResultCode.Error);
                }

                // 2. 根据生产工单中的计划ID获取生产计划信息
                if (productionOrder.ProductionPlanId == Guid.Empty)
                {
                    return ApiResult<List<GetProcessDto>>.Fail("生产工单未关联生产计划", ResultCode.Error);
                }

                var productionPlan = await productionPlanRepository.AsQueryable()
                    .Where(pp => pp.Id == productionOrder.ProductionPlanId && !pp.IsDeleted)
                    .FirstAsync();

                if (productionPlan == null)
                {
                    return ApiResult<List<GetProcessDto>>.Fail($"关联的生产计划不存在，计划ID: {productionOrder.ProductionPlanId}", ResultCode.Error);
                }

                // 3. 根据生产计划中的BOM ID获取工艺路线信息
                if (productionPlan.BomId == Guid.Empty)
                {
                    return ApiResult<List<GetProcessDto>>.Fail("生产计划未关联BOM", ResultCode.Error);
                }

                var routingResult = await _bomService.GetRoutingByBomIdAsync(productionPlan.BomId);
                if (!routingResult.IsSuc)
                {
                    return ApiResult<List<GetProcessDto>>.Fail(routingResult.Msg ?? "获取工艺路线信息失败", routingResult.Code);
                }

                // 4. 根据工艺路线ID获取工序信息
                if (routingResult.Data == null || routingResult.Data.Id == Guid.Empty)
                {
                    return ApiResult<List<GetProcessDto>>.Fail("工艺路线信息不完整", ResultCode.Error);
                }

                var processesResult = await _bomService.GetProcessesByRouteIdAsync(routingResult.Data.Id);
                if (!processesResult.IsSuc)
                {
                    return ApiResult<List<GetProcessDto>>.Fail(processesResult.Msg ?? "获取工序信息失败", processesResult.Code);
                }

                return ApiResult<List<GetProcessDto>>.Success(processesResult.Data ?? new List<GetProcessDto>(), ResultCode.Success);
            }
            catch (Exception ex)
            {
                return ApiResult<List<GetProcessDto>>.Fail($"获取生产工单工序信息失败：{ex.Message}", ResultCode.Error);
            }
        }

        /// <summary>
        /// 批量新增工单任务
        /// </summary>
        /// <param name="dto">批量工单任务信息</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> BatchAddWorkOrderTasks(BatchAddWorkOrderTaskDto dto)
        {
            try
            {
                // 1. 验证输入数据
                if (dto.Tasks == null || !dto.Tasks.Any())
                {
                    return ApiResult.Fail("工单任务列表不能为空", ResultCode.Error);
                }

                // 2. 收集所有生产工单ID和任务编号，用于批量验证
                var productionOrderIds = dto.Tasks.Select(t => t.ProductionOrderId).Distinct().ToList();
                var taskNumbers = dto.Tasks.Select(t => t.TaskNumber).ToList();

                // 3. 批量验证生产工单是否存在
                var existingProductionOrders = await productionorderbase.AsQueryable()
                    .Where(po => productionOrderIds.Contains(po.Id) && !po.IsDeleted)
                    .Select(po => po.Id)
                    .ToListAsync();

                var nonExistingOrderIds = productionOrderIds.Except(existingProductionOrders).ToList();
                if (nonExistingOrderIds.Any())
                {
                    return ApiResult.Fail($"以下生产工单不存在或已被删除：{string.Join(", ", nonExistingOrderIds)}", ResultCode.Error);
                }

                // 4. 批量验证任务编号是否重复（与数据库中已存在的任务编号比较）
                var existingTaskNumbers = await workOrderTaskRepository.AsQueryable()
                    .Where(wt => taskNumbers.Contains(wt.TaskNumber) && !wt.IsDeleted)
                    .Select(wt => wt.TaskNumber)
                    .ToListAsync();

                var duplicateTaskNumbers = taskNumbers.Intersect(existingTaskNumbers).ToList();
                if (duplicateTaskNumbers.Any())
                {
                    return ApiResult.Fail($"以下任务编号已存在：{string.Join(", ", duplicateTaskNumbers)}", ResultCode.Error);
                }

                // 5. 验证任务编号在本次批量中是否重复
                var duplicateInBatch = taskNumbers.GroupBy(x => x)
                    .Where(g => g.Count() > 1)
                    .Select(g => g.Key)
                    .ToList();

                if (duplicateInBatch.Any())
                {
                    return ApiResult.Fail($"本次批量中以下任务编号重复：{string.Join(", ", duplicateInBatch)}", ResultCode.Error);
                }

                // 6. 验证每个任务的时间逻辑
                var invalidTimeTasks = dto.Tasks.Where(t => t.PlanStartTime >= t.PlanEndTime).ToList();
                if (invalidTimeTasks.Any())
                {
                    var invalidTaskNumbers = invalidTimeTasks.Select(t => t.TaskNumber).ToList();
                    return ApiResult.Fail($"以下任务的时间设置无效（计划开工时间必须早于计划完工时间）：{string.Join(", ", invalidTaskNumbers)}", ResultCode.Error);
                }

                // 7. 验证任务数据的完整性
                var invalidTasks = new List<string>();
                foreach (var task in dto.Tasks)
                {
                    if (string.IsNullOrWhiteSpace(task.TaskNumber))
                        invalidTasks.Add($"任务编号不能为空");
                    if (string.IsNullOrWhiteSpace(task.TaskName))
                        invalidTasks.Add($"任务名称不能为空");
                    if (task.ProductionOrderId == Guid.Empty)
                        invalidTasks.Add($"生产工单ID不能为空");
                    if (task.PlanQuantity <= 0)
                        invalidTasks.Add($"计划数量必须大于0");
                }

                if (invalidTasks.Any())
                {
                    return ApiResult.Fail($"数据验证失败：{string.Join("; ", invalidTasks)}", ResultCode.ValidationError);
                }

                // 8. 创建工单任务实体列表
                var workOrderTasks = new List<WorkOrderTaskEntity>();
                var currentTime = DateTime.UtcNow;

                foreach (var taskDto in dto.Tasks)
                {
                    var workOrderTask = new WorkOrderTaskEntity
                    {
                        Id = Guid.NewGuid(),
                        SequenceNumber = taskDto.SequenceNumber,
                        TaskNumber = taskDto.TaskNumber?.Trim(),
                        TaskName = taskDto.TaskName?.Trim(),
                        ProductionOrderId = taskDto.ProductionOrderId,
                        StationName = taskDto.StationName?.Trim(),
                        ProcessCode = taskDto.ProcessCode?.Trim(),
                        ProcessName = taskDto.ProcessName?.Trim(),
                        ProcessFlow = taskDto.ProcessFlow?.Trim(),
                        ProcessType = taskDto.ProcessType?.Trim(),
                        TaskColor = taskDto.TaskColor?.Trim(),
                        PlanQuantity = taskDto.PlanQuantity,
                        ActualQuantity = 0, // 新增时实际数量为0
                        PlanStartTime = taskDto.PlanStartTime,
                        PlanEndTime = taskDto.PlanEndTime,
                        ActualStartTime = null, // 新增时实际开工时间为空
                        ActualEndTime = null, // 新增时实际完工时间为空
                        PlanDuration = taskDto.PlanDuration,
                        ActualDuration = null, // 新增时实际用时为空
                        Status = taskDto.Status?.Trim() ?? "待开始",
                        ProcessRouteId = taskDto.ProcessRouteId,
                        ProcessStepId = taskDto.ProcessStepId,
                        Priority = taskDto.Priority,
                        Remarks = taskDto.Remarks?.Trim(),
                        CreatedAt = currentTime,
                        UpdatedAt = currentTime,
                        IsDeleted = false
                    };

                    workOrderTasks.Add(workOrderTask);
                }

                // 9. 批量保存到数据库
                var result = await workOrderTaskRepository.InsertRangeAsync(workOrderTasks);
                if (!result)
                {
                    return ApiResult.Fail("批量保存工单任务失败", ResultCode.Error);
                }

                return ApiResult.Success( ResultCode.Success);
            }
            catch (Exception ex)
            {
                return ApiResult.Fail($"批量新增工单任务失败：{ex.Message}", ResultCode.Error);
            }
        }

        /// <summary>
        /// 修改生产工单状态
        /// </summary>
        /// <param name="dto">修改生产工单状态信息</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> UpdateProductionOrderStatus(UpdateProductionOrderStatusDto dto)
        {
            try
            {
                // 1. 验证输入数据
                if (dto == null)
                {
                    return ApiResult.Fail("修改数据不能为空", ResultCode.ValidationError);
                }

                if (string.IsNullOrWhiteSpace(dto.Status))
                {
                    return ApiResult.Fail("工单状态不能为空", ResultCode.ValidationError);
                }

                // 2. 验证生产工单是否存在
                var existingOrder = await productionorderbase.AsQueryable()
                    .Where(po => po.Id == dto.Id && !po.IsDeleted)
                    .FirstAsync();

                if (existingOrder == null)
                {
                    return ApiResult.Fail("生产工单不存在或已被删除", ResultCode.NotFound);
                }

                // 3. 验证状态值是否有效
                var validStatuses = new[] { "待排产", "未开始", "进行中", "已完成", "已暂停", "已关闭" };
                if (!validStatuses.Contains(dto.Status.Trim()))
                {
                    return ApiResult.Fail($"无效的工单状态：{dto.Status}。有效状态包括：{string.Join(", ", validStatuses)}", ResultCode.ValidationError);
                }

                // 4. 更新生产工单状态
                existingOrder.Status = dto.Status.Trim();
                existingOrder.UpdatedAt = DateTime.UtcNow;
                existingOrder.UpdatedBy = dto.UpdatedBy?.Trim() ?? "system";

                // 5. 保存到数据库
                var result = await productionorderbase.UpdateAsync(existingOrder);
                if (!result)
                {
                    return ApiResult.Fail("更新生产工单状态失败", ResultCode.Error);
                }

                return ApiResult.Success(ResultCode.Success);
            }
            catch (Exception ex)
            {
                return ApiResult.Fail($"修改生产工单状态失败：{ex.Message}", ResultCode.Error);
            }
        }
    }
}
